var roomDao = require('../DAO/room');
var stepDao = require('../DAO/step');
var usersDao = require('../DAO/users');

async function getRoomList() {
  var rooms = await roomDao.selectAllRooms();
  return rooms;
};

async function joinRoom(roomid, userid, color) {
  var rooms = await roomDao.selectRoomById(roomid);
  // 获取这个房间
  var room = rooms[0];
  var hType = room.colorHuser;
  var bType = room.colorBuser;
  // 如果想加入黑房
  if (color == 'H') {
    // 如果黑方已经有人,并且不是自己
    if (hType && (hType && String(hType) != String(userid))) {
      return false;
    }
  }
  if (color == 'B') {
    if (bType && (bType && String(bType) != String(userid))) {
      return false;
    }
  }
  var userInfos =  await usersDao.selectUserById(userid);
  var userInfo = {};
  if (userInfos.length > 0) {
    userInfo = userInfos[0];
  }
  var username = userInfo.username;
  await roomDao.insertRoomColor(roomid, userid, username, color);
  await roomDao.insertUserRoom(roomid, userid);
  return true;
}
 
async function ready(roomid, color, userid, username) {
  if (color == 'B') {
    await roomDao.updateWhite(roomid, userid, username, 30);
  } else if (color == 'H') {
    await roomDao.updateBlack(roomid, userid, username, 30);
  }
  var allReady = await isAllReady(roomid);
  if (allReady) {
    await roomDao.updateRoomStatus(roomid, 40);
  }
  return true;
}

async function isAllReady(roomid) {
  var result = false;
  var roomInfo = await roomDao.selectRoomById(roomid);
  var { blackStatus, whiteStatus } = roomInfo;
  if (blackStatus == 30 && whiteStatus == 30) {
    result = true;
  }
  return result;
}

async function getRoomById(roomid) {
  return await roomDao.selectRoomById(roomid);
}

async function addStep(x, y, type, userid, roomid) {
  var steps = await stepDao.selectSteps(roomid);
  if (steps.length > 0) {
    var step = steps[steps.length - 1].toJSON();
    if (type == step.type) {
      return false;
    }
  }
  await stepDao.insertStep(x, y, type, userid, roomid);
  return true;
}

async function getSteps(roomid) {
  var steps = await stepDao.selectSteps(roomid);
  return steps;
}

async function creatRoom(roomname, userid, blackUser, whiteUser, chessSize, letNum, username) {
  var blackName, whiteName;
  if (blackUser) {
    let userInfo =  await usersDao.selectUserById(blackUser);
    blackName = userInfo.username;
  }
  if (whiteUser) {
    let userInfo =  await usersDao.selectUserById(whiteUser);
    whiteName = userInfo.username;
  }
  return await roomDao.insertRoom(roomname, userid, blackUser, whiteUser, chessSize, letNum, blackName, whiteName, username);
}

module.exports = {
  getRoomList,
  joinRoom,
  ready,
  getRoomById,
  addStep,
  getSteps,
  creatRoom
};
  